<template>
  <div class="post-create-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <div class="header-title">
            <h1>发布新帖子</h1>
            <p>分享你的想法和经验</p>
          </div>
        </div>
      </div>
    </div>

    <div class="page-content">
      <div class="create-container">
        <!-- 表单卡片 -->
        <el-card class="form-card">
          <el-form
            ref="postFormRef"
            :model="postForm"
            :rules="postRules"
            label-position="top"
            class="post-form"
          >
            <!-- 标题输入 -->
            <el-form-item label="标题" prop="title">
              <el-input
                v-model="postForm.title"
                placeholder="请输入帖子标题"
                maxlength="100"
                show-word-limit
                clearable
              />
            </el-form-item>

            <!-- 分类 -->
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model="postForm.categoryId" placeholder="请选择分类" style="width: 100%">
                <el-option
                  v-for="category in categories"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>

            <!-- 内容 -->
            <el-form-item label="内容" prop="content">
              <el-input
                v-model="postForm.content"
                type="textarea"
                :rows="12"
                placeholder="请输入帖子内容，支持 Markdown 语法"
                maxlength="5000"
                show-word-limit
                resize="vertical"
              />
            </el-form-item>

            <!-- 摘要 -->
            <el-form-item label="摘要（可选）" prop="summary">
              <el-input
                v-model="postForm.summary"
                type="textarea"
                :rows="3"
                placeholder="简要描述帖子内容"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>

            <!-- 设置选项 -->
            <el-form-item label="设置">
              <el-checkbox v-model="postForm.allowComment">允许评论</el-checkbox>
              <el-checkbox v-model="postForm.isTop" v-if="isAdmin" style="margin-left: 20px"
                >置顶帖子</el-checkbox
              >
            </el-form-item>

            <!-- 操作按钮 -->
            <el-form-item>
              <div class="form-actions">
                <el-button @click="$router.go(-1)">取消</el-button>
                <el-button @click="saveDraft" :loading="savingDraft">保存草稿</el-button>
                <el-button type="primary" @click="publishPost" :loading="publishing"
                  >发布帖子</el-button
                >
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { ElMessage, FormInstance } from "element-plus";
// 移除不需要的图标导入
import { createPost, type PostCreateRequest, type CategoryDTO } from "@/api/posts";
import { getCategories } from "@/api/categories";

const router = useRouter();
const store = useStore();

// 响应式数据
const postFormRef = ref<FormInstance>();
const publishing = ref(false);
const savingDraft = ref(false);

const categories = ref<CategoryDTO[]>([]);

// 表单数据
const postForm = reactive({
  title: "",
  content: "",
  summary: "",
  categoryId: null as number | null,
  isTop: false,
  allowComment: true,
});

// 表单验证规则
const postRules = {
  title: [
    { required: true, message: "请输入帖子标题", trigger: "blur" },
    { min: 5, max: 100, message: "标题长度在 5 到 100 个字符", trigger: "blur" },
  ],
  content: [
    { required: true, message: "请输入帖子内容", trigger: "blur" },
    { min: 10, max: 5000, message: "内容长度在 10 到 5000 个字符", trigger: "blur" },
  ],
  categoryId: [{ required: true, message: "请选择分类", trigger: "change" }],
};

// 计算属性
const isAdmin = computed(() => {
  const user = store.getters["auth/user"];
  return user?.roles?.some((role: any) => role.name === "ADMIN") || false;
});

// 移除不需要的计算属性和函数

// 加载分类列表
const loadCategories = async () => {
  try {
    // 尝试从API获取分类列表
    try {
      const response = await getCategories();
      categories.value = response;
      return;
    } catch (apiError) {
      console.warn("API获取分类失败，使用模拟数据:", apiError);
    }

    // 模拟数据（当API不可用时使用）
    const mockCategories: CategoryDTO[] = [
      {
        id: 1,
        name: "技术交流",
        description: "技术讨论",
        sort: 1,
        isActive: true,
        createTime: "2024-01-01T00:00:00",
        updateTime: "2024-01-01T00:00:00",
        postCount: 10,
      },
      {
        id: 2,
        name: "生活随笔",
        description: "生活分享",
        sort: 2,
        isActive: true,
        createTime: "2024-01-01T00:00:00",
        updateTime: "2024-01-01T00:00:00",
        postCount: 8,
      },
      {
        id: 3,
        name: "学习笔记",
        description: "学习心得",
        sort: 3,
        isActive: true,
        createTime: "2024-01-01T00:00:00",
        updateTime: "2024-01-01T00:00:00",
        postCount: 6,
      },
      {
        id: 4,
        name: "项目展示",
        description: "项目分享",
        sort: 4,
        isActive: true,
        createTime: "2024-01-01T00:00:00",
        updateTime: "2024-01-01T00:00:00",
        postCount: 4,
      },
    ];

    categories.value = mockCategories;
  } catch (error) {
    console.error("Failed to load categories:", error);
    ElMessage.error("加载分类列表失败");
  }
};

// 发布帖子
const publishPost = async () => {
  if (!postFormRef.value) return;

  try {
    await postFormRef.value.validate();

    publishing.value = true;

    // 准备发送的数据
    const postData: PostCreateRequest = {
      title: postForm.title.trim(),
      content: postForm.content.trim(),
      summary: postForm.summary?.trim() || postForm.content.substring(0, 200),
      categoryId: Number(postForm.categoryId!), // 确保是数字类型
      tags: [],
      status: 1, // 1为发布状态
      isTop: postForm.isTop,
      allowComment: postForm.allowComment,
      priority: 0,
    };

    console.log("发布帖子数据:", postData);

    // 调用API发布帖子
    const result = await createPost(postData);
    console.log("发布成功返回:", result);

    ElMessage.success("帖子发布成功！");
    // 跳转到帖子列表页面
    router.push("/posts");
  } catch (error: any) {
    console.error("Publish post error:", error);
    console.error("Error details:", {
      status: error.response?.status,
      statusText: error.response?.statusText,
      data: error.response?.data,
      message: error.message,
      config: error.config,
    });

    let errorMessage = "发布失败，请重试";
    if (error.response?.data?.message) {
      errorMessage = error.response.data.message;
    } else if (error.message) {
      errorMessage = error.message;
    }

    ElMessage.error(errorMessage);
  } finally {
    publishing.value = false;
  }
};

// 保存草稿
const saveDraft = async () => {
  if (!postForm.title.trim() && !postForm.content.trim()) {
    ElMessage.warning("请至少填写标题或内容");
    return;
  }

  savingDraft.value = true;
  try {
    // 这里应该调用API保存草稿
    // await createPost({
    //   ...postForm,
    //   status: 'draft'
    // });

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));

    ElMessage.success("草稿保存成功");
  } catch (error) {
    ElMessage.error("保存草稿失败");
  } finally {
    savingDraft.value = false;
  }
};

// 移除不需要的函数

// 获取分类名称
const getCategoryName = (categoryId: number | null) => {
  if (!categoryId) return "未分类";
  const category = categories.value.find((c: CategoryDTO) => c.id === categoryId);
  return category ? category.name : "未知分类";
};

// 组件挂载
onMounted(() => {
  loadCategories();
});
</script>

<style scoped lang="scss">
.post-create-page {
  background-color: #f5f5f5;
  min-height: 100vh;

  .page-header {
    margin-bottom: 24px;
    background-color: #f5f7fa;
    padding: 20px 24px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      max-width: 800px;
      margin: 0 auto;
    }

    .header-left {
      .header-title {
        h1 {
          margin: 0 0 8px 0;
          font-size: 24px;
          color: #2c3e50;
        }

        p {
          margin: 0;
          color: #666;
        }
      }
    }
  }

  .page-content {
    max-width: 800px;
    margin: 0 auto;
    padding: 0 20px;

    .create-container {
      .form-card {
        margin-bottom: 20px;
      }

      .form-actions {
        display: flex;
        gap: 12px;
        justify-content: flex-end;
        margin-top: 20px;
      }
    }
  }

  @media (max-width: 768px) {
    .page-content {
      padding: 0 10px;
    }
  }
}
</style>
